package com.lib.framework.ext

/**
 * AppCompatActivity 扩展接口
 *
 * @author keanbin
 */

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.annotation.IdRes
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction

/**
 * 替换fragment
 */
fun AppCompatActivity.replaceFragmentInActivity(fragment: Fragment, frameId: Int) {
    supportFragmentManager.transact {
        replace(frameId, fragment)
    }
}

/**
 * 添加 fragment
 */
fun AppCompatActivity.addFragmentToActivity(fragment: Fragment, tag: String) {
    supportFragmentManager.transact {
        add(fragment, tag)
    }
}

/**
 * 设置 ActionBar
 */
fun AppCompatActivity.setupActionBar(@IdRes toolbarId: Int, action: ActionBar.() -> Unit) {
    setSupportActionBar(findViewById(toolbarId))
    supportActionBar?.run {
        action()
    }
}

/**
 * 启动页面
 */
fun Context.startActivity(cls: Class<*>, bundle: Bundle? = null) {
    val intent = Intent(this, cls)
    if (bundle != null) {
        intent.putExtras(bundle)
    }

    if (this !is Activity) {
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    }

    startActivity(intent)
}

/**
 * 启动页面
 */
fun AppCompatActivity.startActivity(cls: Class<*>, bundle: Bundle? = null) {
    val intent = Intent(this, cls)
    if (bundle != null) {
        intent.putExtras(bundle)
    }
    startActivity(intent)
}

/**
 * 启动页面
 */
fun AppCompatActivity.startActivityForResult(
    cls: Class<*>,
    requestCode: Int,
    bundle: Bundle? = null
) {
    val intent = Intent(this, cls)
    if (bundle != null) {
        intent.putExtras(bundle)
    }
    startActivityForResult(intent, requestCode)
}

/**
 * 执行FragmentManager 的 transaction，并commit()
 */
private inline fun FragmentManager.transact(action: FragmentTransaction.() -> Unit) {
    beginTransaction().apply {
        action()
    }.commit()
}